<!-- 文件所有权归北京优博泰克 -->
<template>
    <el-dialog title="后台地址设置" v-model="showModal" width="300px" :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form ref="fromInstance" :model="formModel" label-width="90px" label-position="left">
            <el-form-item label="后台IP" required>
                <el-input v-model="formModel.m_ip"></el-input>
            </el-form-item>
            <el-form-item label="后台端口" required>
                <el-input v-model="formModel.m_port"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button size="default" @click="handleClose">取 消</el-button>
            <el-button size="default" type="primary" @click="connectadress(1)" :loading="loading">测试连接</el-button>
            <el-button size="default" type="primary" @click="connectadress(2)">确认</el-button>
        </span>
    </el-dialog>
</template>
<script setup>
import { reactive, toRefs, ref, computed } from 'vue'
import { useCach } from '@/store/cach'
import { ElMessage } from 'element-plus'
import api from '@/api'

let cachInfo = useCach()

let fromInstance = ref(null)

let state = reactive({
    formModel: {
        m_ip: '',
        m_port: '',
    },
    loading: false
})
let { formModel, loading } = toRefs(state)

let showModal = computed(() => cachInfo.showModal)
let modalStatus = computed(() => cachInfo.modalStatus)


console.log(showModal, modalStatus, '==')

let handleClose = () => {
    cachInfo.changeShowModal(false)
    cachInfo.changeModalStatus('')
}

//连接地址
let connectadress = (type) => {
    //验证端口格式
    fromInstance.value.validate(async (valid) => {
        if (!valid) return

        if (type == 1) {
            //测试连接
            state.loading = true
            let url = 'http://' + state.formModel.m_ip + ":" + state.formModel.m_port + '/admin'
            let res = await api.getaxiosdata(url)
            if (res) {
                ElMessage({
                    message: '连接成功',
                    type: 'success'
                })
            }
            ElMessage.error('获取数据失败')
            state.loading = false
            return
        }

        if (type == 2) {
            state.loading = true
            localStorage.setItem("m_ip", state.formModel.m_ip)
            localStorage.setItem("m_port", state.formModel.m_port)
            state.loading = false
            handleClose()
            location.reload() //页面刷新
        }
    })
}
</script>
<style scoped></style>